﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace Pisces
{
	/**
     * created by wangqiang
    **/
	public class HttpModule : AbstractMonoSingletonModule<HttpModule>, InterfaceEntityLiftcycle
	{
		
		/// <summary>
		/// 发送http post
		/// </summary>
		/// <param name="url"></param>
		/// <param name="content"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		public int sendHttpPostAsync(string url, string content, Action<CoreHttpResponse> callback)
		{
			if (callback == null)
			{
				PiscesLog.error($"http请求, url:{url}callback为空，无法发送http请求");
			}
			
			StartCoroutine(doSendHttpPostAsync(url, content, callback));
			return 0;
		}

		private IEnumerator doSendHttpPostAsync(string url, string content, Action<CoreHttpResponse> callback)
		{
			List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
			formData.Add(new MultipartFormDataSection(content));

			UnityWebRequest request = UnityWebRequest.Post(url, formData);
			yield return request.SendWebRequest();

			if (request.result != UnityWebRequest.Result.Success)
			{
				Debug.Log(request.error);
			}
			
			CoreHttpResponse httpResponse = new CoreHttpResponse();
			httpResponse.Code = request.responseCode;
			httpResponse.Content = request.downloadHandler.text;
			
			callback(httpResponse);
		}

		/// <summary>
		/// 发送http请求，异步等待返回
		/// </summary>
		/// <param name="url"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		public int sendHttpGetAsync(string url, Action<CoreHttpResponse> callback)
		{
			if (callback == null)
			{
				PiscesLog.error($"http请求, url:{url}callback为空，无法发送http请求");
			}
			
			StartCoroutine(doSendHttpGetAsync(url, callback));
			return 0;
		}
		
		/// <summary>
		/// 执行http发送请求
		/// </summary>
		/// <param name="url"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		private IEnumerator doSendHttpGetAsync(string url, Action<CoreHttpResponse> callback)
		{
			UnityWebRequest request = UnityWebRequest.Get(url);
			request.timeout = 10;

			yield return request.SendWebRequest();

			if (request.result != UnityWebRequest.Result.Success)
			{
				PiscesLog.error("网络请求失败，url=" + url + ", error=" + request.error);
			}
			
			CoreHttpResponse httpResponse = new CoreHttpResponse();
			httpResponse.Code = request.responseCode;
			httpResponse.Content = request.downloadHandler.text;
			
			callback(httpResponse);
		}
		
	}
}